import { DomPosition } from "../@types/index";
import { PointerPosition } from "../@types/index"
import { getDomPosition } from "../document/index";
import { getPointerPosition } from './getPointer'

/**
 * 拖拽事件
 * @param element 拖砖元素
 * @param targetElement  目标控制元素
 * @param isRelative 相对距离
 * @param onMouseMove
 * @param onMouseDown 鼠标按下
 */
export const dragEvent = (
    element:HTMLElement | object,
    targetElement:HTMLElement | object,
    isRelative:boolean = false,
    onMouseMove:Function = () => {},
    onMouseDown:Function = () => {}
) => {
    let targetElementPosition:DomPosition | null // 目标元素
    let mouseDownPosition:PointerPosition // 鼠标按下记录
    if(!element) return console.error('未选取到元素')
    const fn = (event:MouseEvent) => {
        const mouseMovePosition = getPointerPosition(event) // 实时指针
        const targetElementLivePosition = getDomPosition(<HTMLElement>targetElement,isRelative) // 实时targetDom变化
        //@ts-ignore
        const dragX = mouseMovePosition.x - mouseDownPosition.x // 移动的x
        //@ts-ignore
        const dragY = mouseMovePosition.y - mouseDownPosition.y // 移动的y
        onMouseMove && onMouseMove({
            targetElementPosition,
            targetElementLivePosition,
            mouseDownPosition,
            mouseMovePosition,
            dragX,
            dragY
        })
    }
    //@ts-ignore
    element.addEventListener('mousedown', (event:MouseEvent) => {
        targetElementPosition = getDomPosition(<HTMLElement>targetElement,isRelative) // 按下时的目标dom元素
        mouseDownPosition = getPointerPosition(event) // 按下时的指针元素
        onMouseDown && onMouseDown({
            mouseDownPosition,
            targetElementPosition
        })
        window.document.addEventListener('mousemove', fn,false)
    })
    window.document.addEventListener('mouseup', () => window.document.removeEventListener('mousemove',fn))
}
